package com.bookstore.servlet.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bookstore.model.CartItem;
import com.bookstore.model.Order;
import com.bookstore.model.ReceiverAddress;
import com.bookstore.model.User;
import com.bookstore.service.ReceiverAddressService;
import com.bookstore.service.ServiceFactory;

@WebServlet("/order.do")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String METHOD_CONFIRM = "0";
	public static final String METHOD_SUBMIT = "1";
	public static final String METHOD_ADDRESS = "2";
	public static final String METHOD_FINISH = "3";

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		HttpSession session = request.getSession();
		Map<Integer, CartItem> map = (Map<Integer, CartItem>) session.getAttribute("s_car");
		if (method != null) {
			switch (method) {
			case OrderServlet.METHOD_CONFIRM:
				confirm(request, response, map);
				break;
			case OrderServlet.METHOD_SUBMIT:
				submit(request, response);
				break;
			case OrderServlet.METHOD_ADDRESS:
				address(request, response);
				break;
			case OrderServlet.METHOD_FINISH:
				finish(request, response);
				break;
			}
		}
	}

	private void address(HttpServletRequest request, HttpServletResponse response) {
		int userId = ((User) request.getSession().getAttribute("s_user")).getId();
		List<ReceiverAddress> addresses = null;
		try {
			addresses = ServiceFactory.getReceiverAddressService().findByUserId(userId);
			JSONObject jsonObject = new JSONObject();
			JSONArray array = new JSONArray();
			for (ReceiverAddress address : addresses) {
				jsonObject = (JSONObject) JSON.toJSON(address);
				array.add(jsonObject);
			}
			jsonObject.put("address", array);
			PrintWriter out = response.getWriter();
			out.print(jsonObject.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void confirm(HttpServletRequest request, HttpServletResponse response, Map<Integer, CartItem> map)
			throws ServletException, IOException {
		request.setAttribute("totalDang", total(map));
		request.setAttribute("s_car", map);
		request.getRequestDispatcher("/WEB-INF/view/order/order_info.jsp").forward(request, response);
	}

	private double total(Map<Integer, CartItem> map) {
		double totalPrice = 0.0;
		for (Map.Entry<Integer, CartItem> entry : map.entrySet()) {
			totalPrice += entry.getValue().getNum() * entry.getValue().getPro().getDangPrice();
		}
		BigDecimal bigDecimal = new BigDecimal(totalPrice);
		BigDecimal bd = bigDecimal.setScale(2, bigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}

	private void submit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/order/address_form.jsp").forward(request, response);
	}

	private void finish(HttpServletRequest request, HttpServletResponse response) {
		ReceiverAddress address = new ReceiverAddress();
		Order order = new Order();
		HttpSession session = request.getSession();
		String receiveName = request.getParameter("receiveName");
		String fullAddress = request.getParameter("fullAddress");
		String postalCode = request.getParameter("postalCode");
		String phone = request.getParameter("phone");
		String mobile = request.getParameter("mobile");

		int userId = ((User) session.getAttribute("s_user")).getId();

		Map<Integer, CartItem> map = (Map<Integer, CartItem>) session.getAttribute("s_car");

		if (map.isEmpty()) {
			
		}

		address.setUserId(userId);
		address.setFullAddress(fullAddress);
		address.setReceiveName(receiveName);
		address.setPostalCode(postalCode);
		address.setPhone(phone);
		address.setMobile(mobile);

		order.setFullAddress(address.getFullAddress());
		order.setUserId(userId);
		order.setMobile(address.getMobile());
		order.setOrderDesc("desc");
		order.setOrderTime(System.currentTimeMillis());
		order.setPhone(address.getPhone());
		order.setPostalCode(address.getPostalCode());
		order.setReceiveName(address.getReceiveName());
		order.setStatus(0);

		ReceiverAddressService receiverAddressService = ServiceFactory.getReceiverAddressService();
		try {
			
			if (receiverAddressService.findById(new Integer(request.getParameter("add"))) == null) {
				receiverAddressService.save(address);
			}
			order.setTotalPrice(total(map));
			ServiceFactory.getOrderService().save(order);
			map.clear();
			session.setAttribute("s_car", map);
			session.setAttribute("order", order);
			request.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
